package config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * 1.创建spring security java 配置文件
 *  creates a Servlet Filter known as the springSecurityFilterChain
 * @author chen
 *
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

	 @Bean(name="authenticationManagerBean")
	 @Override
	 public AuthenticationManager authenticationManagerBean() throws Exception {
	     return super.authenticationManagerBean();
	 }
	 
	
	@Autowired	
	UserDetailsService userDetailsService;

	@Autowired //构造全局的(parent)AuthenticationManager
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
       /* auth
            .inMemoryAuthentication()
                .withUser("chen").password("123456").roles("USER");*/
//		  ShaPasswordEncoder encoder = new ShaPasswordEncoder();
		//配置自定义userDetailService
          auth.userDetailsService(userDetailsService);//.passwordEncoder(encoder);
    }
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
			 http.csrf().disable()
			 .authorizeRequests().antMatchers("/login").permitAll()
			 .antMatchers("/oauth/token").permitAll()//OAuth 认证服务器endpoint，默认的获取token的controller的map路径
			 .and()
			 .authorizeRequests().antMatchers("/hello**").access("hasRole('ROLE_USER')")
	         .and()
	         .authorizeRequests().anyRequest().hasRole("USER")
	         .and()
	         	.formLogin()
	         	.loginPage("/login").failureUrl("/login?error")
	      
	         	.usernameParameter("username").passwordParameter("password")
	        .and()
	        	.logout().logoutSuccessUrl("/login?logout")
	         .and();
		
	}
}
